﻿<html>
<head>
<script type="text/javascript">
	function confirmar(){
		if(!confirm("Processo realizado com sucesso\n" +
					"Deseja realizar outro cadastro de post?")){
			window.location = 'index.php';
		}
	}
</script>
<head>

<body onload="<script type='te'>alert('teste ok')</script>">

<h1>Cadastro de Post</h1>

	<form action="criarPost.php" method="post">
		Titulo:<br />
		<input type="text" name="txtTitulo" id="txtTitulo" size="63" />
		<br />
		<br />
		Usuario:
		<br />
		<input type="text" name="txtUsuario" id="txtUsuario" />
		<br />
		<br />
		Conteúdo:
		<br />
		<textarea rows="7" cols="50" name="txtConteudo" id="txtConteudo"></textarea>
		<br />	
		<input type="submit" name="Enviar" id="Enviar" value="Enviar" />
		<br />
		<a href="index.php">Voltar</a>
	</form>
</body>
</html>

<?php
	if($_POST){
		$txtTitulo   = $_POST["txtTitulo"];
		$txtUsuario  = $_POST["txtUsuario"];
		$txtConteudo = $_POST["txtConteudo"];
		$data 		 = date("d/m/Y H:i:s"); 
		
		if(!file_exists('../blog.xml')){
			$xml = new DomDocument('1.0', "UTF-8");
			$blog = $xml->appendChild($xml->createElement('blog'));
			
			$posts    		 		= $blog->appendChild($xml->createElement('posts'));
			$post 	  		 		= $posts->appendChild($xml->createElement('post'));
			$postAttrIdPost  		= $xml->createAttribute('idPost');
			$postAttrIdUsuer 		= $xml->createAttribute('idUsuario');
			$postAttrIdPost->value  = '1';
			$postAttrIdUsuer->value = '1';
			$post->appendChild($postAttrIdPost);
			$post->appendChild($postAttrIdUsuer);
			$post->appendChild($xml->createElement('titulo',$txtTitulo));
			$post->appendChild($xml->createElement('conteudo',$txtConteudo));
			$post->appendChild($xml->createElement('data', $data));
			
			$xml->formatOutput = true;
			$xml->save('../blog.xml');
			
		}else{
			$xml = new DomDocument();
			$xml->formatOutput = true;
			
			$xml->load('../blog.xml');
						
			$posts = $xml->getElementsByTagName('posts')->item(0);
			$postID = $xml->getElementsByTagName('post');
			$ultimoId;
			
			foreach($postId as $Id){
				$ultimoId = $Id->getAttribute('idPost') + 1;
			}
			
			$post 	  		 		= $posts->appendChild($xml->createElement('post'));
			$postAttrIdPost  		= $xml->createAttribute('idPost');
			$postAttrIdUsuer 		= $xml->createAttribute('idUsuario');
			$postAttrIdPost->value  = $ultimoId;
			$postAttrIdUsuer->value = '1';
			$post->appendChild($postAttrIdPost);
			$post->appendChild($postAttrIdUsuer);
			$post->appendChild($xml->createElement('titulo',$txtTitulo));
			$post->appendChild($xml->createElement('conteudo',$txtConteudo));
			$post->appendChild($xml->createElement('data', $data));
			
			$xml->formatOutput = true;
			
			if($xml->save('../blog.xml')){
				echo "<script>confirmar();</script>";
		    }else{
				echo "<script>alert('Erro ao salvar o arquivo XML');</script>";
			}
		}
		
	}else{
		//nada a fazer
	}
?>